/**
 * Copyright (c) 2011, Jason Gardner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.freecake.bonejams.database;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import org.freecake.bonejams.model.Album;
import org.freecake.bonejams.model.Mp3File;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Vector;

import org.cmc.music.metadata.ImageData;
import org.cmc.music.metadata.IMusicMetadata;
import org.cmc.music.metadata.MusicMetadata;
import org.cmc.music.metadata.MusicMetadataSet;
import org.cmc.music.myid3.MyID3;

public class MusicCollection extends Service {
    final String databaseName ="BoneJams";
	Database database = null;
	private int fileCountAdded = 0;
	private int filesOnDisk = 0;
	
	//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  Binder Stuff
	
	public class MusicCollectionBinder extends Binder {
		public MusicCollection getMusicCollection() {
			return MusicCollection.this;
		}
	}	
		
	@Override
	public IBinder onBind(Intent intent) {						 
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			database = new Database(databaseName, 1);
		} else {
            Log.e(getClass().getName(), "SD Card not mounted!");                    
		}			
		return mcBinder;
	}	
	
	@Override
	public boolean onUnbind(Intent intent) {
	    database.close();
	    return false;
	}		
	
    private final IBinder mcBinder = new MusicCollectionBinder();

    //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  Public Music Collection access	
	
	public void rebuildCollection() {
	    fileCountAdded = 0;
	    database.clear();
		File rootDir = new File("/mnt/sdcard/Music");
		recurseDirectory(rootDir);
		Log.i(getClass().getName(), "Database successfully recreated. " + fileCountAdded + "/" + filesOnDisk);
	}
	
	public ArrayList<Mp3File> getAllSongs() {
		ArrayList<Mp3File> songs = database.getAllSongs();
		return songs;
	}
	
	public ArrayList<Album> getAllAlbums() {
		ArrayList<Album> albums = database.getAllAlbums();
		return albums;
	}	
	
	public String[] getAllArtists() {
		String[] artists = database.getAllArtists();
		return artists;
	}
	
	public String[] getPlaylists() {
	    Vector playlists = new Vector();
		File files[] = new File("/mnt/sdcard/Music/Playlists").listFiles();
		if (files != null) {
            for (File file : files) {			
                if (!file.isDirectory() && file.getName().substring(file.getName().length()-5,file.getName().length()).equals(".plst")) {
                    playlists.add(file.getName().substring(0, file.getName().length()-5));
                }
            }
		}
		return (String[]) playlists.toArray(new String[playlists.size()]);     
	}
	
	public ArrayList<Mp3File> getSongsOnAlbum(Album album) {
		ArrayList<Mp3File> songs = database.getSongsOnAlbum(album.title, album.artist);
		return songs;	    
	}
	
	public ArrayList<Mp3File> getSongsByArtist(String artist) {
		ArrayList<Mp3File> songs = database.getSongsByArtist(artist);
		return songs;	    
	}

	public ArrayList<Mp3File> getSongsInPlaylist(String playlistFile) {
	    ArrayList<Mp3File> songs = new ArrayList<Mp3File>();
	    InputStream is = null;
        try {           
            File file = new File("/mnt/sdcard/Music/Playlists/" + playlistFile + ".plst");
            is = new FileInputStream(file);        
            if (is != null) {
                InputStreamReader ir = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(ir);
                String line;
                while ((line = br.readLine()) != null) {                    
                    if (line.length() > 0) {
                        songs.add(database.getSongByFileName(line));
                    }
                }
            }
        } catch (Exception e) {
            Log.e(getClass().getName(), "Error loading playlist", e);
        } finally {
            try {
                is.close();
            } catch (Exception e2) {
                //ignore
            }
        }
		return songs;	    
	}	
	
	//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  Private members	
	
	private void recurseDirectory(File directory) {
		File files[] = directory.listFiles();
		for (File file : files) {			
			if (file.isDirectory()) {
				recurseDirectory(file);
			} else if (file.getName().substring(file.getName().length()-4,file.getName().length()).equals(".mp3")) {
			    filesOnDisk++;
				if (addToCollection(file) == true) {
				     fileCountAdded++;   
				}
				if (filesOnDisk%50==0) {
				    Log.i(getClass().getName(), "Processed " + filesOnDisk + " files");    
				}
			}
		}
	}
	
	private boolean addToCollection(File file) {
	    try {
            MusicMetadataSet mp3set = new MyID3().read(file);
            IMusicMetadata mp3data = mp3set.getSimplified();
            if (mp3data.getSongTitle() == null ||
                mp3data.getArtist() == null ||
                mp3data.getAlbum() == null) {
                Log.w(getClass().getName(), "Unable to add file (bad metadata): " + file.getAbsolutePath());
                Log.w(getClass().getName(), mp3set.toString());
                file.delete();
                return false;
            } else {
                database.insertMP3File(file.getAbsolutePath(), mp3data.getSongTitle(), mp3data.getArtist(), mp3data.getAlbum());
                return true;
            }
        } catch (Exception e) {
            Log.w(getClass().getName(), "Could not add file to the database: " + file.getAbsolutePath(), e);
        }
        return false;
	}	
		
}
